/* 环境变量写入 */
const { resolve } = require('./index')
const configData = require(resolve('micro-config'))

/**
 * 根据entry计算入口页面
 * @param {String} entry
 */
function getPages(entry) {
  const { css, js, deferJs } = configData
  const projectConfig = require(resolve(`src/entry/${ entry }/config.json`))

  const pages = {
    entry: `src/entry/${ entry }/main.js`,
    template: 'public/index.html',
    filename: 'index.html',
    favicon: 'public/favicon.ico',
    title: projectConfig.title,
    chunks: ['chunk-vendors', 'chunk-common', 'index'],
    cdn: {
      js: js.concat(projectConfig.js || []),
      deferJs: deferJs.concat(projectConfig.deferJs || []),
      css: css.concat(projectConfig.css || []),
    }
  }

  return {
    index: pages
  }
}

/**
 * 获取忽略打包数据
 * @param {String} entry 入口文件夹名
 */
function getExternals(entry) {
  const { externals } = configData

  const config = require(resolve(`src/entry/${ entry }/config.json`))
  const entryExternals = config.externals || {} // 提前判空

  return {
    ...externals,
    ...entryExternals
  }
}

module.exports = function(entryData) {
  process.env.VUE_APP_ENTRY = entryData.entry
  process.env.port = entryData.port
  process.env.distPath = entryData.distPath

  /* pages数据 */
  process.env.pages = JSON.stringify(getPages(entryData.entry))
  /* 不打包的数据 */
  process.env.externals = JSON.stringify(getExternals(entryData.entry))
}
